﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.Seedwork;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Application.Seedwork;
using Huirui.Cavan.Domain.MainBoundedContext.StockModule;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;

namespace Huirui.Cavan.Application.MainBoundedContext.StockModule
{
    public class StockInitialBalanceAppService : BaseAppService<StockInitialBalance, long, StockInitialBalanceSearch, IStockInitialBalanceRepository>, IStockInitialBalanceAppService
    {
        private IWareHouseAppService WareHouseAppService { get; set; }
        private IStockAppService StockAppService { get; set; }

        public override BoolGenericResult<StockInitialBalance> Add(StockInitialBalance entity)
        {
            Init();
            BoolGenericResult<StockInitialBalance> result = new BoolGenericResult<StockInitialBalance>();
            if (entity.IsNull())
            {
                throw new ArgumentNullException("");
            }
            this.WareHouseAppService = this.SpringContext.GetObject(StockModuleConst.WAREHOUSEAPPSERVICE) as IWareHouseAppService;
            this.StockAppService = this.SpringContext.GetObject(StockModuleConst.STOCKAPPSERVICE) as IStockAppService;

            if (entity.Stock.IsNotNull() && entity.Stock.Id.IsNotEmpty())
            {
                entity.Stock = this.StockAppService.GetById(entity.Stock.Id);
            }
            if (entity.WareHouse.IsNotNull() && entity.WareHouse.Id.IsNotEmpty())
            {
                entity.WareHouse = this.WareHouseAppService.GetById(entity.WareHouse.Id);
            }

            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            StockManager stockManager = new StockManager(employee);
            result = stockManager.AddStockInitialBalance(entity.Stock, entity.WareHouse, entity.InitialDate, entity.Number, entity.UnitCost);

            if (result.IsSuccess)
            {
                this.StockAppService.Update(entity.Stock);
                base.Add(result.Object);
            }
            return result; ;
        }
    }
}
